package Psh::Strategy::Db;

require Psh::Strategy;
require Psh::Options;
require Psh::Sql;

@Psh::Strategy::Db::ISA=('Psh::Strategy');

#Psh::Support::Builtins::build_autoload_list();

sub new { Psh::Strategy::new(@_) }

# this is basically a wrapper for the dbcore builtin that consumes lines
# instead of tokens so that > < do not break up the sql command
# it has to unalias the commands, since that must happen after the strategies are applied
sub consumes {
	if ($Psh::Sql::full_line) {
		return Psh::Strategy::CONSUME_LINE;
	} else {
		return Psh::Strategy::CONSUME_TOKENS;
	}
}

sub runs_before {
	return qw(built_in);
}

sub applies {
	my $line= ${$_[1]};
	my @words = split(" " , $line);
	#Psh::Util::print_debug("checking if strategy_db applies:$line.$words[0]\n");
        return 'db' if ($words[0] eq "db");

	my $new_line = $Psh::Support::Alias::aliases{$words[0]};
	if ($new_line) {
		@words = split(" " , $new_line);
		#Psh::Util::print_debug("checking if strategy::db applies to alias:$line.$words[0]\n");
        	return 'db' if ($words[0] eq "db");
	}
}

sub execute {
	my $line= ${$_[1]};

	#Psh::Util::print_debug("running strategy db:$line\n");
	# at this point $line may still be the alias and it may not have the db
	my @words = split(/\s/, $line);
        if ($words[0] ne "db") {
		my $new_command = $Psh::Support::Alias::aliases{$words[0]};
		shift(@words); # remove the alias from the command word list
		if ($new_command =~ s/^db\s*//) { 
			# remove the db from the new command, then add it to the word list
			unshift(@words,$new_command); # add the alias expansion to it
		} else {
			Psh::Util::print_error("error: Db strategy examined the alias and thought it applied, but now it is missing the db\n");
			return(0,undef);
		}
	} else {
		# if it does start with 'db', then remove it before sending to builtin
		shift @words;
	}
	$line = join(" ", @words);

	no strict 'refs';
	Psh::Util::print_debug("sending to bi_dbcore: [$line][" . join(",",@words) . "]\n");
	return (1,sub { &Psh::Builtins::Dbcore::bi_dbcore($line,\@words); }, [], 0, undef );
}

1;
